package com.review.llm;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

// Minimal provider using local Ollama CLI or fallback to echo JSON
public class LlmProvider {

	private final ObjectMapper mapper = new ObjectMapper();

	public JsonNode analyze(String prompt) throws Exception {
		String model = System.getenv().getOrDefault("OLLAMA_MODEL", "qwen2.5-coder:7b");
		List<String> cmd = new ArrayList<>();
		cmd.add("ollama");
		cmd.add("run");
		cmd.add(model);
		cmd.add(prompt);
		try {
			ProcessBuilder pb = new ProcessBuilder(cmd);
			pb.redirectErrorStream(true);
			Process p = pb.start();
			StringBuilder sb = new StringBuilder();
			try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
				String line;
				while ((line = br.readLine()) != null) sb.append(line).append('\n');
			}
			int code = p.waitFor();
			if (code == 0) {
				String out = sb.toString();
				try { return mapper.readTree(out); } catch (Exception ignored) { return mapper.createObjectNode().put("raw", out); }
			}
		} catch (Exception ignored) {}
		return mapper.createObjectNode().put("message", "LLM not available");
	}
}

